var app = new Vue({
	el: '#app',
	data: {
		list: [],
		id: 0,

		current: {
			title: '',
			completed: false,
			desc: '....',
			remind_at: '2021-10-01',
		}
	},


	// el 被新创建的 vm.$el 替换, 挂在成功	
	mounted: function () {
		// console.log('mounted...')
		this.list = ms.get('list');
		// console.log(this.list);
	},


	methods: {
		// copy obj 对象 
		deepcopy: function (obj) {
			var copyed = Object.assign({}, obj);
			return copyed
		},


		find_index: function (id) {
			var index = this.list.findIndex(function (item) {
				return item.id === id;
			});
			return index;
		},

		// 从list 获取当前 最大的id 
		find_list_max_id: function () {

			// var cur_id = Math.max.apply(Math, this.list.map(function (item) { return item.id }))
			// if (Math.abs(cur_id) === Infinity) {
			// 	return 0;
			// }
			// return cur_id;


			let n = this.list.length;
			if (!n) {
				return n;
			}
			return this.list[n - 1].id;
		},



		merge: function () {
			// console.log('add a plan ..');
			var is_updated, id;
			is_updated = id = this.current.id;
			if (is_updated) {
				this.update(id);
			} else {
				this.add();
			}
			// plan 计划表 清空
			this.reset_current();

		},

		// 添加一个 plan
		add: function () {
			var title = this.current.title;
			console.log('this.list', this.list);
			if (!title) {
				console.log('no title');
			} else {
				var todo = this.deepcopy(this.current);
				// 自己生成一个id 
				todo.id = this.next_id();
				// console.log(todo);
				this.list.push(todo);
			}

		},

		remove: function (id) {
			var index = this.find_index(id);
			this.list.splice(index, 1);
			// console.log(this.list);
		},

		update: function (id) {
			// console.log('update begin.. id:', id);
			// console.log('updated id:', id);
			// 拿到当前要更新的索引
			var index = this.list.findIndex(function (item) {
				return item.id === id;
			});
			// console.log('index:', index);
			// update plan 
			// var copyed = Object.assign({}, this.current);
			var copyed = this.deepcopy(this.current);
			// Vue更新 list 方法 
			Vue.set(this.list, index, copyed);
		},

		set_current: function (todo) {
			// 注意这里copy 
			this.current = this.deepcopy(todo);
		},

		reset_current: function () {
			this.set_current({})
		},

		/*
		 设置一个自增id 
		*/
		next_id: function () {
			// n = this.list.length;
			let n = this.find_list_max_id();
			this.id = ++n;
			return this.id;
		}

	},



	watch: {
		list: {
			deep: true,
			handler: function (new_list, old) {
				console.log('watch execute... new_list:', new_list);
				if (new_list) {
					ms.set('list', new_list);
				} else {
					ms.set('list', []);
				}

			}
		}
	}

});




// todo  
;
(function () {


})();



/*


方法使用:
Object.assign({},this.current);



生命周期 函数

https://cn.vuejs.org/v2/guide/instance.html#%E5%AE%9E%E4%BE%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90

*/
